package org.xurui.sxl.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.xurui.sxl.protocol.cache.ConcurrentMapCache;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 发短信息给设备
 */
@Slf4j
public class CmdCodec_SMSINFO implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.SMSINFO.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return true;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //设备回复格式：*XX,YYYYYYYYYYYYYYY,V4,SMSINFO,seq,para,HHMMSS,S,latitude,D,longitude,G,speed,pdop,DDMMYY,tracker_status#
        //设备回复示例：*LX,2020916301,V4,SMSINFO,173030,6F9619FF-8B86-D011-B42D-00C04FC964FF,E59B9EE5AEB6E59083E9A5ADE59097EFBC9F,E788B8E788B8,2020-08-30 10:00:00,173031,A,2212.8745,N,11346.6574,E,14.28,2.8,220902,FFFFFFFF#
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        String[] payloadArr = payload.replaceAll("\\*","").split(",");
        String deviceId = payloadArr[1];
        report.setDeviceId(deviceId);
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(deviceId+"_"+CommandEnum.SMSINFO.name()+"_"+payloadArr[4]);
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = deviceId+"_"+payloadArr[4];
        }

        report.setFunctionId(CommandEnum.SMSINFO.name());
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        String para=payloadArr[5]+","+BinaryUtils.hexStr2Str(payloadArr[6])+","+BinaryUtils.hexStr2Str(payloadArr[7])+","+payloadArr[8];

        Map<String, Object> properties = new HashMap<>();
        properties.put("para",para);
        properties.put("uptime",payloadArr[9]);
        properties.put("s",payloadArr[10]);
        properties.put("latitude",BinaryUtils.getWgs84LonLat(payloadArr[11],"lat"));
        properties.put("d",payloadArr[12]);
        properties.put("longitude",BinaryUtils.getWgs84LonLat(payloadArr[13],"lon"));
        properties.put("g",payloadArr[14]);
        properties.put("speed", NumberUtils.parseDouble(payloadArr[15]));
        properties.put("pdop",NumberUtils.parseDouble(payloadArr[16]));
        properties.put("upday", payloadArr[17]);
        String trackerStatusHex = payloadArr[18];


        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        report.setOutput(properties);

        //TODO 更新状态
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //格式：*XX,YYYYYYYYYYYYYYY,SMSINFO,HHMMSS,SMSUID,SMSCONTENT,SMSSENDER,SMSTIME#
        //例子：*LX,2020916301,SMSINFO,173030,6F9619FF-8B86-D011-B42D-00C04FC964FF,E59B9EE5AEB6E59083E9A5ADE59097EFBC9F,E788B8E788B8,2020-08-30 10:00:00#
        //参数说明： SMSUID 短消息 ID；可以用 GUID 来描述；用于回传读取状态
        //参数说明： SMSCONTENT 短消息内容；UTF-8 编码；
        //参数说明： SMSSENDER 短信发送者；UTF-8 编码；
        //参数说明： SMSTIME 短信时间；YYYY-MM-DD HH:MM:SS
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String smsUID= UUID.randomUUID().toString();
            if(paramsMap.get("smsUID")!=null && !paramsMap.get("smsUID").equals("")){
                smsUID=paramsMap.get("smsUID").toString();
            }
            String smsContent="";
            if(paramsMap.get("smsContent")!=null && !paramsMap.get("smsContent").equals("")){
                smsContent=paramsMap.get("smsContent").toString();
            }
            String smssEnder="";
            if(paramsMap.get("smssEnder")!=null && !paramsMap.get("smssEnder").equals("")){
                smssEnder=paramsMap.get("smssEnder").toString();
            }
            String smsTime="";
            if(paramsMap.get("smsTime")!=null && !paramsMap.get("smsTime").equals("")){
                smsTime=paramsMap.get("smsTime").toString();
            }

            String time = SxlMessageUtils.getTimeHHMMSS();//DateFormatUtils.format(new Date(),"HHmmss");
            /*StringBuffer sb = new StringBuffer();
            sb.append("*");
            sb.append(zzs);//TODO 需要修改成根据设备动态加载
            sb.append(",");
            sb.append(message.getDeviceId());
            sb.append(",");
            sb.append(CommandEnum.SMSINFO.name());
            sb.append(",");
            sb.append(time);
            sb.append(",");
            sb.append(smsUID);
            sb.append(",");
            sb.append(BinaryUtils.str2HexStr(smsContent));
            sb.append(",");
            sb.append(BinaryUtils.str2HexStr(smssEnder));
            sb.append(",");
            sb.append(smsTime);
            sb.append("#");*/
            ConcurrentMapCache.getInstance().set(message.getDeviceId()+"_"+CommandEnum.SMSINFO.name()+"_"+time,message.getMessageId(),60*3*1000);
            //return EncodedMessage.simple(Unpooled.wrappedBuffer(sb.toString().getBytes()));

            return SxlMessageUtils.SxlCmd.getInstance()
                .appendAndAddSeparator(zzs)
                .appendAndAddSeparator(message.getDeviceId())
                .appendAndAddSeparator(CommandEnum.SMSINFO.name())
                .appendAndAddSeparator(time)
                .appendAndAddSeparator(smsUID)
                .appendAndAddSeparator(BinaryUtils.str2HexStr(smsContent))
                .appendAndAddSeparator(BinaryUtils.str2HexStr(smssEnder))
                .append(smsTime).buildEncodeMessage();
        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.WIFISCAN.name(),message);
            }
            return null;
        }
    }
}
